package com.mengfou;


import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author 梦否
 * @date 2025/06/28 22:19
 */
public class ClassLoaderLearn {

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader(ClassLoader.getSystemClassLoader());
        Class<?> aClass = Class.forName("com.mengfou.MFWebSocketServer", true, myClassLoader);
    }

    public static class MyClassLoader extends ClassLoader {

        private String path = "D:\\My Proj\\testForLearn\\test-target\\classes";

        private ClassLoader originalClassLoader;
        protected MyClassLoader(ClassLoader parent) {
            originalClassLoader = parent;
        }

        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            try {
                System.out.println("find class: " + name);
                return originalClassLoader.loadClass(name);
            } catch (ClassNotFoundException e) {
                System.out.println("find from custom classloader.");
                String replace = name.replace(".", "\\\\");
                File file = new File(path, replace+".class");
                if(file.exists()) {
                    byte[] data = FileUtils.loadByteArray(file);
                    return defineClass(null, data, 0, data.length);
                }
                throw new ClassNotFoundException("file not exist. path: " + file.getAbsolutePath());
            }
        }
    }
}
